//
//  OAuthViewController.swift
//  weibo_swift
//
//  Created by dulinlong on 15/6/28.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController ,UIWebViewDelegate{

    let WB_Client_ID = "2806351036"
    let WB_Redirect_URL = "http://www.baidu.com"
    let WB_Client_Secret = "9f5b30f039cdc1426c758af23ebb7c87"
    
    
    override func loadView() {
        
        view = webView
        title = "新浪微博"
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuthPage()
    }
    
    func close(){
        print("----close")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    deinit{
        SVProgressHUD.dismiss()
    }


    func loadOAuthPage(){
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL)")
        
        webView.loadRequest(NSURLRequest(URL: url!))
    
    }
 
    /// 懒加载webview
    lazy var webView: UIWebView = {
        let web = UIWebView()
        web.delegate = self
        return web
        }()
    
    
    //MARK - WebViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print("----" + "\(request)")
        
        let urlString = request.URL?.absoluteString
        //如果是weibo网页,继续加载
        if !urlString!.hasPrefix(WB_Redirect_URL){
            return true
        }
        
        //如果是回调地址,更具url的内容,判断是剖有授权码
        let query = request.URL?.query
        let codeStr = "code="
        
        if query!.hasPrefix(codeStr){
            let code = query!.substringFromIndex(advance(codeStr.endIndex, 0)) as String
            loadAceesToken(code)
        }else{
            close()
        }
        
        return false
    }
    
     func webViewDidStartLoad(webView: UIWebView){
    
//        SVProgressHUD.showInfoWithStatus("demo", maskType: SVProgressHUDMaskType.Black)
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView){
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?){
        
        SVProgressHUD.dismiss()
    }


    /// 加载token
    private func loadAceesToken(code: String){
        //1.url
        let urlString = "oauth2/access_token"
        let parameters = ["client_id":WB_Client_ID,"client_secret":WB_Client_Secret
        ,"grant_type":"authorization_code","code":code,"redirect_uri":WB_Redirect_URL]
        
        //设置响应格式是二进制
//        NetWorkTool.sharedNetWorkTool().responseSerializer = AFHTTPResponseSerializer()
        
        NetWorkTool.sharedNetWorkTool().POST(urlString, parameters: parameters, success: { (_, JSON) -> Void in
            //加载token
            //完善用户信息
            UserAccount(dict: JSON as! [String: AnyObject]).loadUserInfo { (account, error) -> () in
                if account != nil{
                    //1.设置全局变量
                    sharedUserAccount = account
                    
                    //2.通知跳转界面
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootControllerNotification, object: true)
                    //3.关闭界面
                    self.close()
                    
                    return
                }
                
                print(error)
                SVProgressHUD.showInfoWithStatus("你的网络不给力")
            }
            
            
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("你的网络不给力")

        }
    }
    

}
